﻿using UnityEngine;
using System.Collections;

public class Motor : MonoBehaviour
{

    public Wheel[] wheels;
    public ParticleSystem smoke;
    public Color smokeColor;

    Color startSmokeColor;

    Rect right, left;

    void Start()
    {
        startSmokeColor = smoke.startColor;
        float y = Screen.height / 2;
        left = new Rect(0, 0, Screen.width / 2, y);
        right = new Rect(Screen.width / 2, 0, Screen.width / 2, y);
    }

	void Update () 
    {
        bool wheelCalled = false;
	    foreach(Touch touch in Input.touches)
        {
            if (left.Contains(touch.position))
            {
                CallToWheels(false);
                wheelCalled = true;
            }
            if (right.Contains(touch.position))
            {
                CallToWheels(true);
                wheelCalled = true;
            }
        }

        if (Input.GetMouseButton(0))
        {
            if (left.Contains(Input.mousePosition))
            {
                CallToWheels(false);
                wheelCalled = true;
            }
            if (right.Contains(Input.mousePosition))
            {
                CallToWheels(true);
                wheelCalled = true;
            }
        }

        float x = Input.GetAxis("Horizontal");
        if (x != 0)
        {
            CallToWheels(x > 0);
            wheelCalled = true;
        }

        if (!wheelCalled)
        {
            StopWheels();
        }
	}

    public void CallToWheels(bool right)
    {
        foreach(Wheel wheel in wheels)
        {
            if (right)
            {
                wheel.Right();
            }
            else
            {
                wheel.Left();
            }
        }
        smoke.startColor = smokeColor;
    }

    void StopWheels()
    {
        foreach(Wheel wheel in wheels)
        {
            wheel.Stop();
        }
        smoke.startColor = startSmokeColor;
    }
}
